<template>
  <!-- 第二部分：商品卡片展示区（无限滚动） -->
  <div class="second-section">
    <div class="section-title">搜索商品: {{ searchKeyword }}</div>
    <div
        class="products-container"
        @scroll="handleScroll"
        ref="productsScrollContainer"
    >
      <div class="products-grid" v-if="products.length > 0">
        <div class="product-card" v-for="(product, index) in products" :key="product.id || index" @click="goProduct(product)">
          <div class="product-img-container">
            <img :src="product.img" alt="商品图片" class="product-img" @error="handleImageError">
            <div class="product-badge" v-if="product.badge">{{ product.badge }}</div>
          </div>
          <div class="product-name">{{ product.name }}</div>
          <div class="product-price">¥{{ product.priceAfter }}</div>
          <div class="product-sales">
            <el-icon class="sales-icon"><Goods /></el-icon>
            {{ product.buyEd}}人已买
          </div>
<!--          <el-button class="add-to-cart" size="small" @click="addToCart(product)">-->
<!--            <el-icon><ShoppingCart /></el-icon>-->
<!--            加入购物车-->
<!--          </el-button>-->
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!isLoading && products.length === 0 && searchPerformed">
        <el-icon><Box /></el-icon>
        <p>暂无相关商品</p>
      </div>

      <!-- 加载指示器 -->
      <div class="loading-indicator" v-if="isLoading">
        <el-spinner />
        <span>加载中...</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { onMounted, ref, watch } from 'vue'
import axios from "axios"
import { Goods, ShoppingCart, Box } from '@element-plus/icons-vue'
import router from "../../router/index.js";

// 使用 Composition API
const route = useRoute()
const searchKeyword = ref('')
const products = ref([])
const isLoading = ref(false)
const currentPage = ref(1)
const hasMore = ref(true)
const searchPerformed = ref(false)
const productsScrollContainer = ref(null)

// 先定义函数，再使用它们
// 执行搜索
const performSearch = async () => {
  if (!searchKeyword.value.trim()) return

  products.value = []
  currentPage.value = 1
  hasMore.value = true
  searchPerformed.value = true
  await loadProducts()
}

// 加载商品数据
const loadProducts = async () => {
  isLoading.value = true
  try {
    // 使用 GET 请求进行搜索
    const response = await axios.get('/api/product/search', {
      params: {
        keyword: searchKeyword.value,
      }
    })

    const newProducts = response.data

    if (currentPage.value === 1) {
      products.value = newProducts || []
    } else {
      products.value = [...products.value, ...newProducts]
    }

    // 简单判断是否还有更多数据（根据返回数量）
    hasMore.value = newProducts.length >= 20 // 假设每页20条数据
  } catch (error) {
    console.error('搜索商品失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 处理滚动事件，实现无限滚动
const handleScroll = () => {
  if (!productsScrollContainer.value) return

  const { scrollTop, clientHeight, scrollHeight } = productsScrollContainer.value

  // 触发无限滚动加载
  if (scrollHeight - scrollTop - clientHeight < 200 && !isLoading.value && hasMore.value) {
    loadMoreProducts()
  }
}

// 加载更多商品
const loadMoreProducts = async () => {
  if (hasMore.value && !isLoading.value) {
    currentPage.value++
    await loadProducts()
  }
}
const goProduct = (product) => {
  // 跳转到商品详情页
  console.log('跳转到商品详情页')
  router.push(`/productMain/${product.id}`)
}
// 添加到购物车
const addToCart = (product) => {
  // 添加到购物车逻辑
  console.log('添加到购物车:', product)
}

// 图片加载失败处理
const handleImageError = (event) => {
  // 图片加载失败时的默认图片
  event.target.src = 'https://via.placeholder.com/200x200?text=商品图片'
}

// 监听路由参数变化（移到函数定义之后）
watch(
    () => route.query,
    (newQuery) => {
      const keyword = newQuery.keyword || newQuery.query || ''
      if (keyword && keyword !== searchKeyword.value) {
        searchKeyword.value = keyword
        performSearch()
      }
    },
    { immediate: true }
)
</script>

<style scoped>
.second-section {
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.products-container {
  height: calc(100vh - 200px);
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.product-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
  transition: box-shadow 0.3s;
  background: #fff;
}

.product-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-img-container {
  position: relative;
  height: 160px;
  margin-bottom: 10px;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-badge {
  position: absolute;
  top: 5px;
  left: 5px;
  background-color: #ff4d4f;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.product-name {
  font-size: 14px;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff4d4f;
  margin-bottom: 5px;
}

.product-sales {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.sales-icon {
  margin-right: 4px;
}

.add-to-cart {
  width: 100%;
  background-color: #ff9a00;
  color: white;
  border: none;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}
</style>
